package es.ibm.santillana.mdm.integration;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

import javax.xml.parsers.ParserConfigurationException;

import com.ibm.mq.MQException;
import com.ibm.pim.lookuptable.LookupTable;
import com.ibm.pim.lookuptable.LookupTableEntry;
import com.ibm.pim.lookuptable.LookupTableManager;

import es.ibm.santillana.mdm.common.util.ConstSantillana;
import es.ibm.santillana.mdm.mqseries.SantillanaMQ;
import es.ibm.santillana.mdm.xml.XMLIntegration;
import es.ibm.santillana.mdm.xml.XMLIntegrationFactory;

/**
 * @author Benito
 *
 */
public class ExportData {

	/**
	 * 
	 */
	private SantillanaMQ cola;
	private Boolean queueActivated = true;
	
	public ExportData() throws IOException {
		Properties prop = new Properties();
		String propertiesName = "params.properties";
		String propertiesPath = ConstSantillana.PROPERTIES_PATH + propertiesName;
		InputStream input = new FileInputStream(propertiesPath);
		prop.load(input);
		
		String tipo = prop.getProperty("exporttype","QUEUE");
		System.out.println(ConstSantillana.exportTypes.valueOf(tipo));
		switch(ConstSantillana.exportTypes.valueOf(tipo)){
			case QUEUE:
				initQueue();
				break;
			case WEBSERVICES:
			case NONE:
			case BOTH:
			default:
		}
	}
	
	private void initQueue(){
		try {
			cola = new SantillanaMQ();
			System.out.println("Valor de cola: ");
			System.out.println(cola);
			queueActivated = true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * Exporta los cambios 
	 * @param item
	 * @param ctxPIM
	 * @return
	 * @throws MQException 
	 */
	public boolean exportXML(IntegrationChanges intChanges){
//		String catalogName = item.getCatalog().getName();
//		String sPk = item.getPrimaryKey();
		
		LookupTableManager lkpMan = intChanges.getContext().getLookupTableManager();
		LookupTable lkp = lkpMan.getLookupTable("System Parameter LKP");
		LookupTableEntry itmLkpUser = lkp.getLookupTableEntry("use.broker");
		
		String sendBroker = (String) itmLkpUser.getAttributeValue("Code_Value_LTS/Value");
		
		if(intChanges.getInsert()!=null && intChanges.getInsert().size()>0){
			try {
				XMLIntegration resultado = XMLIntegrationFactory.getStateXML(ConstSantillana.exportStates.insert, intChanges.getContext(),intChanges.getsCtgName(),intChanges.getsPkItem());
				System.out.println("HAY INSERT");
				//Obtiene el XML a enviar.
				HashMap<String,ArrayList<Modification>> hmInsertAtts = intChanges.getInsert();
				
				String insertXML = resultado.getExportXML(hmInsertAtts);
				
//				System.out.println(insertXML);
								
				if (sendBroker.equals("true")) {
					if(insertXML!=null && !insertXML.equals("") &&  queueActivated){
						System.out.println("VOY A ENVIAR A LA COLA");
						cola.messageQueue.add(insertXML);
						cola.messageNamesQueue.add(intChanges.getsCtgName().concat("_").concat(intChanges.getsPkItem()));
					}
				}
				
				createFileInServer(ConstSantillana.PATH_INSERT, insertXML, intChanges);
				
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				System.out.println(e);
				e.printStackTrace();
				return false;
			}
			
		}else{
			System.out.println("No hay inserts");
		}
		
		if(intChanges.getDelete()!=null && intChanges.getDelete().size()>0){
			try {
				XMLIntegration resultado = XMLIntegrationFactory.getStateXML(ConstSantillana.exportStates.delete, intChanges.getContext(),intChanges.getsCtgName(),intChanges.getsPkItem());
				System.out.println("DELETE");
				//Obtiene el XML a enviar.
				HashMap<String,ArrayList<Modification>> hmDeleteAtts = intChanges.getDelete();
				
				String deleteXML = resultado.getExportXML(hmDeleteAtts);
				
				if (sendBroker.equals("true")) {
					if(deleteXML!=null && !deleteXML.equals("") && queueActivated){
						
						cola.messageQueue.add(deleteXML);
						cola.messageNamesQueue.add(intChanges.getsCtgName().concat("_").concat(intChanges.getsPkItem()));
					}
				}
				createFileInServer(ConstSantillana.PATH_DELETE, deleteXML, intChanges);

			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				System.out.println(e);
				e.printStackTrace();
				return false;
			}
			
		}else{
			System.out.println("No hay deletes");
		}
				
		if(intChanges.getUpdate()!=null && intChanges.getUpdate().size()>0){
			try {
				XMLIntegration resultado = XMLIntegrationFactory.getStateXML(ConstSantillana.exportStates.update, intChanges.getContext(),intChanges.getsCtgName(),intChanges.getsPkItem());
				System.out.println("HAY UPDATE");
				//Obtiene el XML a enviar.
				HashMap<String,ArrayList<Modification>> hmUpdateAtts = intChanges.getUpdate();
				
				String updateXML = resultado.getExportXML(hmUpdateAtts);
				
//				System.out.println(updateXML);
				
				if (sendBroker.equals("true")) {
					if(updateXML!=null && !updateXML.equals("") &&  queueActivated){
						System.out.println("VOY A ENVIAR A LA COLA");
						cola.messageQueue.add(updateXML);
						cola.messageNamesQueue.add(intChanges.getsCtgName().concat("_").concat(intChanges.getsPkItem()));
					}
				}
				createFileInServer(ConstSantillana.PATH_UPDATE, updateXML, intChanges);
				
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				System.out.println(e);
				e.printStackTrace();
				return false;
			}
			
		}else{
			System.out.println("No hay updates");
		}
		
		if (cola.messageQueue.size() > 0) sendMessagesInQueue();
		
		return true;
	}
	
	private void sendMessagesInQueue() {
		
		System.out.println("Mensajes que se van a enviar (Export Data) -> " + cola.messageQueue.size());
		cola.enviaXML();		
	}

	private void createFileInServer(String pathInsert, String XML, IntegrationChanges intChanges) {
		try {
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
			Date date = new Date();
			String dateFormatted = sdf.format(date);
			String xmlName = dateFormatted.concat(intChanges.getsCtgName().concat("_").concat(intChanges.getsPkItem()));
			
			String ruta = pathInsert.concat(xmlName);
	        File archivo = new File(ruta);
	        BufferedWriter bw;

	        if(archivo.exists()) {
				bw = new BufferedWriter(new FileWriter(archivo));
	            bw.write(XML);
	        } else {
	            bw = new BufferedWriter(new FileWriter(archivo));
	            bw.write(XML);
	        }
	        bw.close();
	        
		} catch (IOException e) {
				// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
